package com.peycard.persistence.dao;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.Query;

import com.peycard.persistence.PersistenceException;
import com.peycard.persistence.dao.local.ReaderControlDAOLocal;
import com.peycard.persistence.entities.ReaderControl;

/**
 * Session Bean implementation class ReaderControlDAO
 */
@Stateless
public class ReaderControlDAO extends GenericDAOImpl<ReaderControl, Long> implements ReaderControlDAOLocal {

    /**
     * Default constructor. 
     */
    public ReaderControlDAO() {
       
    }
    
    @Override
    public List<ReaderControl> getAll() throws PersistenceException{
    	try{
    		Query query = getEntityManager().createNamedQuery("findAllReadersControl_1");
    		List<ReaderControl> list = query.getResultList();
    		return list;
    	}catch(Exception e){
    		throw new PersistenceException(e);
    	}
    }
    
    @Override
    public ReaderControl setDown(String idReader, String usr) throws PersistenceException{
    	long idReaderLong = 0l;
    	try{
    		idReaderLong = Long.parseLong(idReader);
    	}catch(NumberFormatException e){
    		return null;
    	}
    	ReaderControl control = super.read(idReaderLong);
    	if(control != null){
    		control.setIsActive(BigDecimal.valueOf(0l));
        	control.setUsername(usr);
        	super.update(control);
    	}
    	return control;
    }

    @Override
    public ReaderControl save(String brand, String model, String platform, String user, String active) throws PersistenceException{
    	ReaderControl entity = new ReaderControl();
    	entity.setBrand(brand);
    	entity.setModel(model);
    	entity.setPlatform(platform);
    	entity.setUsername(user);
    	BigDecimal bd = new BigDecimal(active);
    	entity.setIsActive(bd);
    	Timestamp time = new Timestamp(System.currentTimeMillis());
    	entity.setSaveData(time);
    	ReaderControl entity2 = super.create(entity);
    	return entity2;
    }
    
    @Override
    public ReaderControl update(String brand, String model, String platform, String user, String active) throws PersistenceException {
    	Query query = getEntityManager().createNamedQuery("findReaderControl_1");
    	query.setParameter("brand_1", brand);
    	query.setParameter("model_1", model);
    	ReaderControl reader = (ReaderControl) query.getSingleResult();
    	if(reader == null){
    		return null;
    	}else{
    		BigDecimal bd = new BigDecimal(active);
    		reader.setIsActive(bd);
    		reader.setPlatform(platform);
    		super.update(reader);
    	}
    	return reader;
    }
    
}
